<template>
    <el-dialog title="新增子目" :visible.sync="visible" width="644px" top="5vh !important" append-to-body :close-on-click-modal="false">
        <el-form ref="form" :model="form" :rules="rules" size="medium" label-width="156px">
            <el-form-item :label="parentLabel" prop="chapterSequenceCode">
                <el-select v-model="form.chapterSequenceCode" clearable filterable placeholder="请选择" style="width: 100%" @change="handleChapterChange">
                    <el-option v-for="item in chapterOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
            </el-form-item>
            <el-form-item label="上级清单子目">
                <el-select
                v-model="form.parentCode"
                clearable
                filterable
                remote
                :disabled="!form.chapterSequenceCode"
                :placeholder="form.chapterSequenceCode ? '请输入，仅允许输入数字、字母横杠-' : '请先选择' + parentLabel"
                style="width: 100%"
                :remote-method="remoteMethod"
                @change="handleParentCodeChange"
                >
                    <el-option v-for="item in childrenOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
            </el-form-item>
            <el-form-item label="清单子目编码" prop="listSubitemCode">
                <el-input v-if="type === 1" v-model="form.listSubitemCode" maxlength="200" clearable placeholder="请输入，仅允许输入数字、字母横杠-"></el-input>
                <el-input v-if="type === 2" v-model="form.listSubitemCode" maxlength="200" clearable placeholder="请输入，包含数字、字母横杠-，数字开头和数字结尾，不能为0"></el-input>
            </el-form-item>
            <el-form-item label="清单子目名称" prop="listSubitemName">
                <el-input v-model="form.listSubitemName" maxlength="50" show-word-limit clearable placeholder="请输入"></el-input>
            </el-form-item>
            <el-form-item prop="isChild">
                <div slot="label" style="display: inline-block;">
                    <span>是否存在下级子项 </span>
                    <el-tooltip effect="dark" content="当前清单子目是否存在下一级清单子目" placement="top">
                        <i class="el-icon-info"></i>
                    </el-tooltip>
                </div>
                <el-radio-group v-model="form.isChild" @change="handleChangeIsChild">
                    <el-radio :label="1">存在</el-radio>
                    <el-radio :label="2">不存在</el-radio>
                </el-radio-group>
            </el-form-item>
            <template v-if="form.isChild === 1">
                <el-form-item label="单位">
                    <el-input v-model="form.unitSymbol" disabled placeholder="当前子目存在下级子项时，不可维护单位、数量、单价" clearable></el-input>
                </el-form-item>
                <el-form-item label="暂估数量">
                    <el-input v-model="form.quantity" disabled placeholder="当前子目存在下级子项时，不可维护单位、数量、单价" clearable></el-input>
                </el-form-item>
                <el-form-item label="单价（元）">
                    <el-input v-model="form.price" disabled placeholder="当前子目存在下级子项时，不可维护单位、数量、单价" clearable></el-input>
                    
                </el-form-item>
                <el-form-item label="合价（元）">
                    <el-input v-model="amount" disabled></el-input>
                </el-form-item>
            </template>
            <div v-if="form.isChild === 2">
                <el-form-item prop="unitCode">
                    <div slot="label" style="display: inline-block;">
                        <span>单位 </span>
                        <el-tooltip effect="dark" content="如果有单位缺失，请联系亮风台人员添加" placement="top">
                            <i class="el-icon-info"></i>
                        </el-tooltip>
                    </div>
                    <el-select
                        v-model="form.unitCode"
                        placeholder="请选择"
                        filterable
                        clearable
                        style="width: 100%;"
                        @change="handleChangeUnit"
                    >
                        <el-option
                            v-for="item in unitOptions"
                            :key="item.unitCode"
                            :label="item.unitSymbol"
                            :value="item.unitCode"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="暂估数量" prop="quantity">
                    <el-input v-model="form.quantity" :disabled="!form.unitSymbol" :placeholder="!form.unitSymbol ? '请先选择单位' : quantityPlaceholder" clearable></el-input>
                </el-form-item>
                <el-form-item label="单价（元）" prop="price">
                    <el-input v-model="form.price"  :disabled="!form.unitSymbol || noPrice" :placeholder="noPrice ? '暂无单价' : (!form.unitSymbol ? '请先选择单位' : '请输入单价，可保留两位小数')" clearable style="width: 60%;"></el-input>
                    <el-checkbox v-model="noPrice" style="width: 25%;margin-left: 24px;" @change="handlePriceChange">暂无单价</el-checkbox>
                </el-form-item>
                <el-form-item label="合价（元）">
                    <el-input v-model="amount" disabled></el-input>
                </el-form-item>
            </div>

            <el-form-item label="备注">
                <el-input
                    v-model="form.remark"
                    type="textarea"
                    :autosize="{ minRows: 2, maxRows: 4}"
                    placeholder="请输入"
                    maxlength="100"
                    show-word-limit
                >
                </el-input>
            </el-form-item>
        </el-form>

        <div slot="footer">
            <BaseButton type="recond" @click="cancel">取消</BaseButton>
            <BaseButton @click="submitForm">保存</BaseButton>
        </div>
    </el-dialog>
</template>

<script>
import { ContractModel } from '@/models'
import { isNumber2 } from '@/utils/validate'
import BigNumber from 'bignumber.js'

const validIsNumber2 = (rule, value, callback) => {
    if (!isNumber2(value)) {
        callback(new Error('格式错误'))
    } else {
        callback()
    }
}

export default {
    name: 'ChildSaveOrUpdate',
    props: {
        type: {
            type: Number,
            default: 1 // type=1:普通工程量清单；type=2:计日工
        },
        id: {
            type: [Number, String],
            default: '' // 合同id
        },
        list: {
            type: Array,
            default: () => []
        },
    },
    data() {
        return {
            parentLabel: '章次',
            model: new ContractModel(),
            chapterOptions: [],
            childrenOptions: [],
            visible: false,
            // 表单参数
            form: {
                parentCode: '',
                listSubitemCode: '',
                listSubitemName: '',
                isChild: 1,
                unitCode: null,
                quantity: '',
                price: '',
                remark: ''
            },
            level: 1,
            noPrice: false,
            unitValidateDecimalPlace: 0,
            quantityPlaceholder: '请输入',
            rules: {
                chapterSequenceCode: [{ required: true, message: '请选择', trigger: 'change' }],
                listSubitemCode: [],
                listSubitemName: [{ required: true, message: '请输入', trigger: 'blur' }],
                isChild: [{ required: true, message: '请选择', trigger: 'change' }],
                unitCode: [{ required: true, message: '请选择', trigger: 'change' }],
                quantity: [
                    { required: true, message: '请输入', trigger: 'blur' },
                    { validator: this.validQuantity, trigger: 'blur' }
                ],
                price: [
                    { required: true, message: '请输入', trigger: 'blur' },
                    { validator: validIsNumber2, trigger: 'blur' }
                ]
            },
            unitOptions: []
        }
    },
    computed: {
        amount() {
            const { quantity, price} = this.form
            if ((!quantity && quantity !== '0') || (!price && price !== '0')) {
                return ''
            }
            const total = new BigNumber(this.form.quantity).times(this.form.price).toFixed(2)
            return total
        }
    },
    created () {
        this.getUnitList()
        // 处理下名称
        if (this.type === 1) {
            this.parentLabel = '章次'
            this.getChapterList()
        }
        if (this.type === 2) {
            this.parentLabel = '分类'
            this.getClassifyList()
        }
    },
    methods: {
        handlePriceChange() {
            if (this.noPrice) {
                this.form.remark = '暂无单价'
                this.rules.price = []
                this.form.price = ''
                // 清除表格的price验证
                this.$refs.form.clearValidate('price')
            } else {
                this.form.remark = ''
                this.rules.price = [
                    { required: true, message: '请输入', trigger: 'change' },
                    { validator: validIsNumber2, trigger: 'blur' }
                ]
            }
        },
        handleChapterChange(value) {
            this.childrenOptions = []
            this.form.parentCode = ''
            this.level = 1
            const target = this.chapterOptions.find(item => item.value === value)
            this.form.chapterSequenceName = target.label
        },
        handleParentCodeChange(value) {
            const target = this.childrenOptions.find(item => item.value === value)
            this.form.parentName = target.label
        },
        remoteMethod(query) {
            if (query !== '') {
                this.model.quantitiesListSearch({
                    contractId: this.id,
                    type: this.type,
                    chapterSequenceCode: this.form.chapterSequenceCode,
                    pageNo: 1,
                    pageSize: 1000,
                    listSubitemCode: query
                })
                    .then(res => {
                        // 先把列表中的已添加的数据进行前端静态搜索，前端有下级的字段是isChild
                        const staticList = this.list.filter(item => item.isChild === 1).map(item => {
                            return {
                                value: item.listSubitemCode,
                                label: item.listSubitemCode + ' ' + item.listSubitemName,
                                level: item.level
                            }
                        })
                        const staticOptions = []
                        staticList.forEach(item => {
                            if (item.value.includes(query)) {
                                staticOptions.push(item)
                            }
                        })

                        // 只包含hasChildren为1，存在下级的
                        const options = (res.list || []).filter(item => item.hasChildren === 1).map(item => {
                            return {
                                value: item.listSubitemCode,
                                label: item.listSubitemCode + ' ' + item.listSubitemName,
                                level: item.level
                            }
                        })

                        this.childrenOptions = [...staticOptions, ...options]
                    })
            } else {
                this.childrenOptions = []
            } 
        },
        // 取消按钮
        cancel() {
            this.reset()
            this.visible = false
        },
        open() {
            this.visible = true
            this.reset()
            // 工程量和计日工验证规则不一样
            if (this.type === 1) {
                this.rules.listSubitemCode = [
                    { required: true, message: '请输入', trigger: 'blur' },
                    { validator: this.validCode1, trigger: 'blur' },
                    { validator: this.validCodeUnique, trigger: 'blur' }
                ]
            }
            if (this.type === 2) {
                this.rules.listSubitemCode = [
                    { required: true, message: '请输入', trigger: 'blur' },
                    { validator: this.validCode3, trigger: 'blur' },
                    { validator: this.validCodeUnique, trigger: 'blur' }
                ]
            }

            // 重置下验证规则
            this.$nextTick(() => {
                this.$refs['form'].clearValidate()
            })
        },
        reset() {
            this.form = {
                parentCode: '',
                listSubitemCode: '',
                listSubitemName: '',
                isChild: 1,
                unitCode: null,
                quantity: '',
                price: '',
                remark: ''
            }
            this.childrenOptions = []
            this.noPrice = false
        },
        submitForm() {
            this.$refs['form'].validate((valid) => {
                if (valid) {
                    // 如果选了上级清单子目，则层级为1+上级层级
                    if (this.form.parentCode) {
                        this.level = this.childrenOptions.find(item => item.value === this.form.parentCode).level + 1
                    }

                    const data = {
                        ...this.form,
                        amount: this.amount,
                        contractId: this.id,
                        type: this.type,
                        level: this.level,
                        unitSymbol: this.form.unitSymbol,
                    }
                    this.$emit('success', data)
                    this.visible = false
                }
            })
        },
        getUnitList() {
            this.model.unitList().then(res => {
                this.unitOptions = res || []
            })
        },
        getChapterList() {
            this.model.chapterList().then(res => {
                this.chapterOptions = (res || []).map(item => {
                    return {
                        label: item.listSubitemCode + ' ' + item.listSubitemName,
                        value: item.listSubitemCode
                    }
                })
            })
        },
        getClassifyList() {
            this.model.classifyList().then(res => {
                this.chapterOptions = (res || []).map(item => {
                    return {
                        label: item.listSubitemName,
                        value: item.listSubitemCode
                    }
                })
            })
        },
        handleChangeUnit(value) {
            const target = this.unitOptions.find(item => item.unitCode === value) || {}
            this.unitValidateDecimalPlace = target.decimalPlace
            this.form.unitSymbol = target.unitSymbol
            if (this.unitValidateDecimalPlace === 0) {
                this.quantityPlaceholder = '请输入数量，保留整数'
            } else {
                this.quantityPlaceholder = `请输入数量，可保留${this.unitValidateDecimalPlace}位小数`
            }
        },
        validCode1(rule, value, callback) {
            const regex = /^-?\d+(\-\d+)*$/
            if (!regex.test(value)) {
                callback(new Error('格式错误'))
            } else {
                callback()
            }
        },
        validCode2(rule, value, callback) {
            const regex = /^[1-9][0-9]*(-[0-9]+)*$/
            if (!regex.test(value)) {
                callback(new Error('格式错误'))
            } else {
                callback()
            }
        },
        validCode3(rule, value, callback) {
            const regex = /^[1-9]\d*(-\d+)*$/
            if (!regex.test(value)) {
                callback(new Error('格式错误'))
            } else {
                callback()
            }
        },
        validQuantity(rule, value, callback) {
            console.log('validQuantity')
            const regex = this.createDecimalRegex(this.unitValidateDecimalPlace)
            if (!regex.test(value)) {
                callback(new Error('格式错误'))
            } else {
                callback()
            }
        },
        validCodeUnique(rule, value, callback) {
            this.model.validQuantitiesUnique({
                code: value,
                id: this.form.id || null,
                contractId: this.id,
                type: this.type
            }).then((res) => {
                if (!res) {
                    callback(new Error('清单子目编码已存在'))
                } else {
                    callback()
                }
            })
        },
        createDecimalRegex(places) {
            if (places === 0) {
                return /^\d+$/
            }
            // 生成对应位数小数的正则表达式字符串
            const decimalPart = `(?:\\.(\\d{1,${places}}))?`
            const regexStr = `^\\d+${decimalPart}$`            
            return new RegExp(regexStr)
        },
        handleChangeIsChild() {
            this.unitValidateDecimalPlace = 0
            this.form.unitCode = null
            this.form.unitSymbol = ''
            this.form.quantity = ''
            this.form.price = ''
        }
    }
}
</script>
<style lang="scss" scoped>
.dialog-footer {
    padding: 24px;
    text-align: right;
    border-top: 1px solid #eee;
}
</style>
